package com.yogee.topseller.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.umeng.analytics.MobclickAgent;
import com.yogee.core.base.HttpActivity1;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.SharedPreferencesUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.base.HttpActivity;
import com.yogee.topseller.application.TopellerApplication;
import com.yogee.topseller.bean.MySelfInfo;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.bean.ResultBean1;
import com.yogee.topseller.fragment.DingyueProductFragment;
import com.yogee.topseller.fragment.HomeFragment;
import com.yogee.topseller.fragment.MyFragment;
import com.yogee.topseller.fragment.ProductFragment;
import com.yogee.topseller.fragment.ShouchongFragment;
import com.yogee.topseller.fragment.ShouchongFragment1;
import com.yogee.topseller.fragment.ZhuanyeFragment;
import com.yogee.topseller.fragment.zhoubian.DingyueFragment;
import com.yogee.topseller.fragment.zhoubian.DingyueFragment1;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/6/11.
 */

public class MainActivity1 extends HttpActivity1 {

    @BindView(R.id.rl_home)
    RelativeLayout rl_home;
    @BindView(R.id.rl_product)
    RelativeLayout rl_product;
    @BindView(R.id.rl_shansou)
    RelativeLayout rl_shansou;
    @BindView(R.id.rl_dingyue)
    RelativeLayout rl_dingyue;
    @BindView(R.id.rl_mine)
    RelativeLayout rl_mine;
    @BindView(R.id.pop_bg)
    View popBg;
    @BindView(R.id.img_home)
    ImageView img_home;
    @BindView(R.id.img_product)
    ImageView img_product;
    @BindView(R.id.img_dingyue)
    ImageView img_dingyue;
    @BindView(R.id.img_mine)
    ImageView img_mine;
    @BindView(R.id.tv_home)
    TextView tv_home;
    @BindView(R.id.tv_product)
    TextView tv_product;
    @BindView(R.id.tv_dingyue)
    TextView tv_dingyue;
    @BindView(R.id.tv_mine)
    TextView tv_mine;

    //Fragment管理
    private FragmentManager fragmentManager;
    //Fragment类
    private HomeFragment homeFragment;
    private ProductFragment productFragment;
    private DingyueProductFragment dingyueFragment;
    private MyFragment myFragment;
    private PopupWindow popupWindow_createss;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_mainactivity_new;
    }

    private Handler popupHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    popupWindow_createss.showAtLocation(findViewById(R.id.pop_bg), Gravity.CENTER, 0, 0);
//                    popupWindow_createss.update();
                    break;
            }
        }

    };

    @Override
    protected void initView() {
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        homeFragment = new HomeFragment();
        transaction.add(R.id.main_fragment_container,homeFragment);
        transaction.commit();
        img_home.setSelected(true);
        tv_home.setSelected(true);
//        ShouchongFragment dialogFragment = new ShouchongFragment();
//        dialogFragment.setCancelable(false);
//        dialogFragment.show(getFragmentManager(),"");

        PgyUpdateManager.setIsForced(true); //设置是否强制更新。true为强制更新；false为不强制更新（默认值）。
//        PgyUpdateManager.register(this);
        // 自定义面板
        PgyUpdateManager.register(MainActivity1.this,
                new UpdateManagerListener() {

                    @Override
                    public void onUpdateAvailable(final String result) {

                        // 将新版本信息封装到AppBean中
                        final AppBean appBean = getAppBeanFromString(result);

                        View popupWindowView = LayoutInflater.from(TopellerApplication.app).inflate(R.layout.pop_udpatel, null);

                        popupWindow_createss = new PopupWindow(popupWindowView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                        popupWindow_createss.setOutsideTouchable(true);
                        // 更新内容
                        TextView tv_update_info = (TextView) popupWindowView.findViewById(R.id.tv_update_info);
                        tv_update_info.setText(appBean.getReleaseNote());
                        TextView btn_update = (TextView) popupWindowView.findViewById(R.id.btn_update);
                        TextView tv_version = (TextView) popupWindowView.findViewById(R.id.tv_version);
                        tv_version.setText("升级到版本:"+appBean.getVersionName());

//                        TextView btn_cancels = (TextView) popupWindowView.findViewById(R.id.btn_cancels);
//                        btn_cancels.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                popupWindow_createss.dismiss();
//                            }
//                        });
                        // 点击更新
                        btn_update.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                startDownloadTask(MainActivity1.this,appBean.getDownloadURL());
                            }
                        });
                        popupWindow_createss.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                            }
                        });
                        //显示位置
//                        popupWindow_createss.showAtLocation(findViewById(R.id.pop_bg), Gravity.CENTER, 0, 0);
                        popupHandler.sendEmptyMessageDelayed(0, 1000);
//                        new AlertDialog.Builder(MainActivity.this)
//                                .setTitle("更新")
//                                .setMessage("")
//                                .setNegativeButton(
//                                        "确定",
//                                        new DialogInterface.OnClickListener() {
//
//                                            @Override
//                                            public void onClick(DialogInterface dialog,int which) {
//                                                startDownloadTask(MainActivity.this,appBean.getDownloadURL());
//                                            }
//                                        }).show();
                    }

                    @Override
                    public void onNoUpdateAvailable() {
//                        ShouchongFragment dialogFragment = new ShouchongFragment();
//                        Bundle args = new Bundle();
//                        args.putString("imgUrl",o.getUrlImg());
//                        dialogFragment.setArguments(args);
//                        dialogFragment.setCancelable(false);
//                        dialogFragment.show(getFragmentManager(),"");
//                        getHyZt();
                    }
                });
        phoneId(MySelfInfo.getInstance().getCid());

    }
    private void phoneId(String cid) {

        if(!TextUtils.isEmpty(cid)){
            if(AppUtil.isExamine(MainActivity1.this)){
                HttpManager.getInstance().phoneId(cid, AppUtil.getUserId(TopellerApplication.app)).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
                    @Override
                    public void onNext(ResultBean o) {

                    }
                }, this));
            }
        }
    }

    private void getHyZt(){
        if(AppUtil.isExamine(MainActivity1.this)){
            HttpManager.getInstance().userOrderTypeInfo(AppUtil.getUserId(this)).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean1>() {
                @Override
                public void onNext(ResultBean1 o) {
                    if(!o.getStatus().equals("0")){
                        ShouchongFragment1 dialogFragment = new ShouchongFragment1();
                        Bundle args = new Bundle();
                        args.putString("imgUrl",o.getUrlImg());
                        dialogFragment.setArguments(args);
                        dialogFragment.setCancelable(false);
                        dialogFragment.show(getFragmentManager(),"");
                    }else{

                    }

                }
            }, this));
        }
    }
    //初始化底部菜单选择状态
    private void reTxtSelect(){
        tv_home.setSelected(false);
        tv_product.setSelected(false);
        tv_dingyue.setSelected(false);
        tv_mine.setSelected(false);

        img_home.setSelected(false);
        img_product.setSelected(false);
        img_dingyue.setSelected(false);
        img_mine.setSelected(false);
    }

    public void setDingyue(){
        onClick(findViewById(R.id.rl_dingyue));
    }
    @OnClick({R.id.rl_home,R.id.rl_product,R.id.img_shansou,R.id.rl_dingyue,R.id.rl_mine,R.id.rl_shansou_1})
    public void onClick(View view){
    //v4包导入getSupportFragmentManager，app包使用getFragmentManager，app包3.0后才使用
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        reTxtSelect();
        switch (view.getId()){
            case R.id.rl_home:
                hideAllFragment(transaction);
                tv_home.setSelected(true);
                img_home.setSelected(true);
                if(homeFragment==null){
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.main_fragment_container,homeFragment);
                }else{
                    transaction.show(homeFragment);
                }
                break;
            case R.id.rl_product:
                hideAllFragment(transaction);
                tv_product.setSelected(true);
                img_product.setSelected(true);
                if(productFragment==null){
                    productFragment = new ProductFragment();
                    transaction.add(R.id.main_fragment_container,productFragment);
                }else{
                    transaction.show(productFragment);
                }
                break;
            case R.id.rl_shansou_1:
                if(!AppUtil.isFastDoubleClick()){
                    if(!AppUtil.isExamined(MainActivity1.this)){
                        MobclickAgent.onEvent(MainActivity1.this, "soso_shansou_click_unlogin");
//                    tabHost.setCurrentTab(shansou);
//                    ToastUtils.showToast(MainActivity.this,"点击了闪搜");
                    }else{
//                        MobclickAgent.onEvent(MainActivity1.this, "soso_shansou_click", AppUtil.getUserId(MainActivity1.this));
                        Boolean flag = (Boolean) SharedPreferencesUtils.get(MainActivity1.this,SharedPreferencesUtils.HAVE_FLASH,false);
                        if(flag){
                            startActivity(new Intent().setClass(MainActivity1.this,FlashActivity.class));
                        }else{
                            showSsPop();
                        }
//                        soso_test

                    }
                }

                break;
            case R.id.img_shansou:
                if(!AppUtil.isFastDoubleClick()){
                    if(!AppUtil.isExamined(MainActivity1.this)){
                        MobclickAgent.onEvent(MainActivity1.this, "soso_shansou_click_unlogin");
//                    tabHost.setCurrentTab(shansou);
//                    ToastUtils.showToast(MainActivity.this,"点击了闪搜");
                    }else{
                        MobclickAgent.onEvent(MainActivity1.this, "soso_shansou_click");
                        Boolean flag = (Boolean) SharedPreferencesUtils.get(MainActivity1.this,SharedPreferencesUtils.HAVE_FLASH,false);
                        if(flag){
                            startActivity(new Intent().setClass(MainActivity1.this,FlashActivity.class));
                        }else{
                            showSsPop();
                        }

                    }
                }
//
                break;
            case R.id.rl_dingyue:
                if(AppUtil.isExamined(MainActivity1.this)){
                    hideAllFragment(transaction);
                    tv_dingyue.setSelected(true);
                    img_dingyue.setSelected(true);
                    if(dingyueFragment==null){
                        dingyueFragment = new DingyueProductFragment();
                        transaction.add(R.id.main_fragment_container,dingyueFragment);
                    }else{
                        transaction.show(dingyueFragment);
                    }
                }
                break;
            case R.id.rl_mine:
                if(AppUtil.isExamined(MainActivity1.this)){
                    hideAllFragment(transaction);
                    tv_mine.setSelected(true);
                    img_mine.setSelected(true);
                    if(myFragment==null){
                        myFragment = new MyFragment();
                        transaction.add(R.id.main_fragment_container,myFragment);
                    }else{
                        transaction.show(myFragment);
                    }
                }

                break;
        }
        transaction.commit();
    }

    //隐藏所有Fragment
    public void hideAllFragment(FragmentTransaction transaction){
        if(homeFragment!=null){
            transaction.hide(homeFragment);
        }
        if(productFragment!=null){
            transaction.hide(productFragment);
        }
        if(dingyueFragment!=null){
            transaction.hide(dingyueFragment);
        }
        if(myFragment!=null){
            transaction.hide(myFragment);
        }
    }


    public void showSsPop() {
        View popupWindowView = LayoutInflater.from(TopellerApplication.app).inflate(R.layout.pop_shansou, null);
        int width = 0;
        if (popupWindow_createss == null || !popupWindow_createss.isShowing())
            width = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth()*4/5;
        popupWindow_createss = new PopupWindow(popupWindowView, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow_createss.setOutsideTouchable(true);
        popupWindow_createss.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popBg.setVisibility(View.GONE);
            }
        });

        ImageView img_close_btn = (ImageView) popupWindowView.findViewById(R.id.img_close_btn);
        img_close_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow_createss.dismiss();
            }
        });
        TextView create_shansou_btn = (TextView) popupWindowView.findViewById(R.id.create_shansou_btn);
        create_shansou_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                ToastUtils.showToast(MainActivity.this,"创建闪搜");
                popupWindow_createss.dismiss();
                Intent intent = new Intent();
                intent.setClass(MainActivity1.this, FlashDetailsActivity.class);
                startActivity(intent);
            }
        });
        popupWindow_createss.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow_createss.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popBg.setVisibility(View.GONE);
            }
        });


        //菜单背景色
//        ColorDrawable dw = new ColorDrawable(0xffffffff);
//        popupWindow_createss.setBackgroundDrawable(dw);
        //显示位置
        popupWindow_createss.showAtLocation(popBg, Gravity.CENTER, 0, 0);
        popBg.setVisibility(View.VISIBLE);
    }

    private long mExitTime;
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(popupWindow_createss!=null&&popupWindow_createss.isShowing()){

            }else{
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Object mHelperUtils;
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                } else {
                    finish();
                }
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("app进去后的界面"); //手动统计页面("SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this); //统计时长
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("app进去后的界面"); //手动统计页面("SplashScreen"为页面名称，可自定义)
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PgyUpdateManager.unregister();
    }
}
